package me.spring.cloud.common.components.oss.cloud.util;

import me.spring.cloud.common.components.oss.cloud.CloudStorageService;
import me.spring.cloud.common.components.oss.cloud.exception.OssResourceException;
import me.spring.cloud.common.components.oss.cloud.exception.code.OssCode;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OssSourceSet {

  private static List<String> ossSourceKeyList = new CopyOnWriteArrayList<String>();

  private static Map<String, CloudStorageService> targetOssSourcesMap = new ConcurrentHashMap<>();

  public static Object putTargetOssSourcesMap(String key, CloudStorageService ossSource) {
    ossSourceKeyList.add(key);
    return targetOssSourcesMap.put(key, ossSource);
  }

  /**
   * @Author luffy
   * @Description 删除oss Service
   * @Date 2019-07-02 16:48
   * @Param [key]
   * @Return java.lang.Object
   **/
  public static Object removeTargetOssSourcesMap(String key) {
    try {
      ossSourceKeyList.remove(key);
      return targetOssSourcesMap.remove(key);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new OssResourceException(OssCode.OSS_RESOURCE_ERROR,
          "移除OssSourceSet数据源信息时出现异常，可能由于ossSourceKeyList或targetOssSourcesMap没有该item项");
    }
  }

  public static Map getTargetOssSourcesMap() {
    return targetOssSourcesMap;
  }

  public static CloudStorageService getTargetOssSources(String ossSourceKey) {
    return targetOssSourcesMap.get(ossSourceKey);
  }

  /**
   * @Return boolean
   * @Author luffy
   * @Description 验证是否存在oss
   * @Date 2019-07-02 10:07
   * @Param [ossSourceKey]
   **/
  public static boolean containsOssSource(String ossSourceKey) {
    return ossSourceKeyList.contains(ossSourceKey);
  }
}
